package com.haiyou.dc.mq.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haiyou.common.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;

/**
 * @author huangzl
 */
@RestController
@Slf4j
@Api(tags = "消息操作")
@RequestMapping("/mq")
public class RabbitMqController {

    @Autowired
    private Environment env;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @ApiOperation(value = "发送测试消息")
    @GetMapping("/sendMessage")
    public R sendMessage(@RequestParam String message) throws UnsupportedEncodingException, JsonProcessingException {
        rabbitTemplate.setExchange(env.getProperty("mq.basic.info.exchange"));
        rabbitTemplate.setRoutingKey(env.getProperty("mq.basic.info.routeKey"));
        Message msgBuild = MessageBuilder.withBody(message.getBytes("UTF-8")).build();
//        rabbitTemplate.send(msgBuild);

        Message build = MessageBuilder.withBody(objectMapper.writeValueAsBytes(message)).build();
        rabbitTemplate.convertAndSend(build);

        return R.ok();
    }


}
